import sys
import os
import codecs

def copywrepl(f1,f2,replarr):
	f=codecs.open(f1,"r","utf-8")
	xs=f.read()
	f.close()
	for k,v in replarr.iteritems():
		xs=xs.replace(k,v)
	xs=xs.replace("\r\n","\n")
	f=file(f2,"w")
	f.write(xs.encode("utf-8"))
	f.close()
	

def mkproj(name):
	pname=".\\"+name
	print "making proj "+name
	os.system("rmdir /S/Q "+pname)
	os.system("C:\\dev\\gwt\\webAppCreator.cmd -out "+name+" com.ypaco."+name)
	os.system("rmdir /S/Q "+pname+"\\src\\com\\ypaco\\server");
	os.system("del /Q "+pname+"\\src\\com\\ypaco\\client\\greeting*");
	os.system("del /Q "+pname+"\\war\\WEB-INF\\lib\\*");
	os.system("del /Q "+pname+"\\war\\WEB-INF\\web.xml");
	os.system("del /Q "+pname+"\\README.txt");
	xpath,scr=os.path.split(sys.argv[0])
	copywrepl(xpath+"\\web.xml",pname+"\\war\\WEB-INF\\web.xml",{"{name}":name})
	copywrepl(xpath+"\\gwt.xml",pname+"\\src\\com\\ypaco\\"+name+".gwt.xml",{"{name}":name})
	copywrepl(xpath+"\\emptyclass.java",pname+"\\src\\com\\ypaco\\client\\"+name+".java",{"{name}":name})
	copywrepl(xpath+"\\empty.html",pname+"\\war\\"+name+".html",{"{name}":name})
	copywrepl(xpath+"\\build_win.xml",pname+"\\build.xml",{"{name}":name})
	copywrepl(xpath+"\\build_lin.xml",pname+"\\build_lin.xml",{"{name}":name})
	copywrepl(xpath+"\\.classpath",pname+"\\.classpath",{"{name}":name})
	os.system("cd .\\"+name+" & ant hosted")
	return 0

def main():
	if len(sys.argv)<2:
		print "No argument"
		sys.exit(1)
	sys.exit(mkproj(sys.argv[1]))

if __name__=='__main__':
	main()